# Create your views here.
from blog.models import Post, Comment
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.template import RequestContext
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_http_methods
from django.core.mail import send_mail
from django.core.mail import EmailMessage
from django.forms.fields import email_re
from pykismet import *

def is_valid_email(email):
	return True if email_re.match(email) else False 

def ViewContentForm(request):
	name_error = ""
	email_error = ""
	subject_error = ""
	content_error = ""
	email_valid_error = ""
	spam_error = ""
	debug_email = ""
	if request.method == 'POST':
		# Get Post Variables
		is_submit = request.POST["submit"]
		if (is_submit):
			name = request.POST["name"]
			email = request.POST["email"]
			subject = request.POST["subject"]
			content = request.POST["content"]			
		ak = Akismet('07789caeabcd', 'http://c-pj.net/blog/')
		if_spam = Comment('10.0.42.1', 'Lynx', author=name, email=email, content=content)
		# End Get Post Variables
		if (name == ""):
			name_error = "Name is required"
		if (email == ""):
			email_error = "Email is required"
		if (email_re.match(email)):
			email_valid_error = ""
		else:
			email_valid_error = "Please enter a valid email."
		if (subject == ""):
			subject_error = "Subject is required"
		debug_email = email_re.match(email)
		if (content == ""):
			content_error = "Content is required"
		if(if_spam.is_spam(ak)):
			spam_error = 'Your contact message was detected as spam and therefore was not sent! '
		else:
			spam_error = ""
		if (spam_error == "" and name_error == "" and email_error  == "" and email_valid_error == "" and subject_error  == "" and content_error  == ""):
			compiled_content = name + ' has sent a message to you from the comment form at http://c-pj.net, \n' + name + "'s email is: " + email + '\n' + 'The message they sent was: \n' + content
			recipients = ['cloudpjff7@gmail.com']
			contact_email = EmailMessage(subject, compiled_content, email, recipients)
			contact_email.send()
			return HttpResponseRedirect('/contact/thanks/') # Redirect after POST	
	else:
		name = ""
		email = ""
		subject = ""
		content = ""			
	context = {
		'spam_error' : spam_error,
		'name_error' : name_error,
		'email_error' : email_error,
		'subject_error' : subject_error,
		'content_error' : content_error,
		'email_valid_error' : email_valid_error,
		'name' : name,
		'email' : email,
		'subject' : subject,
		'content' : content,
		'debug_email' : debug_email,
	}
	return render_to_response('contact/view.html', context, context_instance = RequestContext(request))
def Thanks(request):
	context = {}
	return render_to_response('contact/thanks.html', context, context_instance = RequestContext(request))
